package com.lixingye.meowstar.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixingye.meowstar.common.AppResult;
import com.lixingye.meowstar.common.ResultCode;
import com.lixingye.meowstar.dao.UserMapper;
import com.lixingye.meowstar.exception.ApplicationException;
import com.lixingye.meowstar.model.User;
import com.lixingye.meowstar.service.IUserService;
import com.lixingye.meowstar.utils.MD5Util;
import com.lixingye.meowstar.utils.StringUtil;
import com.lixingye.meowstar.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 猫大仙
 * @since 2025-01-14
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    private User selectByUserName(@Param("username") String username){
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getDeleteState,0).orderByDesc(User::getId));
        return users.isEmpty() ? null : users.get(0);
    }


    @Override
    public void createNormalUser(User user) {
        //1.非空校验
        if(user==null || !StringUtils.hasLength(user.getUsername()) ||
        !StringUtils.hasLength(user.getNickname()) || !StringUtils.hasLength(user.getPassword())
        || !StringUtils.hasLength(user.getSalt())){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.查询用户信息
        User userInfo = selectByUserName(user.getUsername());
        if(userInfo!=null){
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //3.新增用户
        //设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insert(user);
        if(row!=1){
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功");

    }
    @Override
    public User getByUsername(String username) {
        if(StringUtil.isEmpty(username)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = getByUsername(username);
        if(user == null){
            log.error(ResultCode.FAILED_LOGIN.toString()+" ,username = "+username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if(!encryptPassword.equals(user.getPassword())){
            log.error(ResultCode.FAILED_LOGIN.toString()+" ,username = "+username+"密码输入错误");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        log.info(ResultCode.SUCCESS.toString()+",username = "+username+"登录成功");
        return user;
    }

    @Override
    public User getByUserId(Long id) {
        if(id == null){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectById(id);
    }
    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id<=0){
            log.error(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectById(id);

        if(user == null){
            log.error(ResultCode.ERROR_IS_NULL.toString() + ",user id = "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int i = userMapper.updateById(updateUser);
        if(i!=1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void deleteOneArticleCountById(Long id) {
        if(id == null || id<=0){
            log.error(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectById(id);

        if(user == null){
            log.error(ResultCode.ERROR_IS_NULL.toString() + ",user id = "+id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int i = userMapper.updateById(updateUser);
        if(i!=1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //参数校验
        if(user == null || user.getId()==null || user.getId()<=0){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existsUser = userMapper.selectById(user.getId());
        if(existsUser==null){
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义标志位,校验所有参数是否同时为空(是否有修改项)
        boolean check = false;
        User updateUser = new User();
        updateUser.setId(user.getId());
        /**
         * 对每个参数进行校验
         */
        if(!StringUtil.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())){
            //查看此用户名是否存在
            User checkUser = selectByUserName(user.getUsername());
            if(checkUser!=null){
                //用户已存在
                log.error(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //无此用户名,进行修改
            updateUser.setUsername(user.getUsername());
            //更新标志位
            check = true;
        }
        if(!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())){
            updateUser.setNickname(user.getNickname());
            //更新标志位
            check = true;
        }
        if(user.getGender()!=null && user.getGender()!=existsUser.getGender()){
            updateUser.setGender(user.getGender());
            if(user.getGender()>2 || user.getGender()<0){
                updateUser.setGender((byte) 2);
            }
            //更新标志位
            check = true;
        }
        if(!StringUtil.isEmpty(user.getEmail()) && !user.getEmail().equals(existsUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            //更新标志位
            check = true;
        }
        if(!StringUtil.isEmpty(user.getPhoneNum()) && !user.getPhoneNum().equals(existsUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            check = true;
        }
        if(!StringUtil.isEmpty(user.getRemark()) && !user.getRemark().equals(existsUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            //更新标志位
            check = true;
        }
        if(check){
            int i = userMapper.updateById(updateUser);
            if(i!=1){
                log.warn(ResultCode.FAILED.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
            }
        }else{
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id == null || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectById(id);
        if(user == null || user.getDeleteState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        String oldPasswordMD5 = MD5Util.md5Salt(oldPassword, user.getSalt());
        if(!oldPasswordMD5.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //生成新的盐
        String salt = UUIDUtil.UUID_32();
        String newPasswordMD5 = MD5Util.md5Salt(newPassword, salt);
        //修改
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(newPasswordMD5);
        updateUser.setSalt(salt);
        int i = userMapper.updateById(updateUser);
        if(i!=1){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
